﻿namespace localsave
{
    export function stringToUtf8Array(str: string): number[]
    {
        var bstr: number[] = [];
        for (var i = 0; i < str.length; i++)
        {
            var c = str.charAt(i);
            var cc = c.charCodeAt(0);
            if (cc > 0xFFFF)
            {
                throw new Error("InvalidCharacterError");
            }
            if (cc > 0x80)
            {
                if (cc < 0x07FF)
                {
                    var c1 = (cc >>> 6) | 0xC0;
                    var c2 = (cc & 0x3F) | 0x80;
                    bstr.push(c1, c2);
                }
                else
                {
                    var c1 = (cc >>> 12) | 0xE0;
                    var c2 = ((cc >>> 6) & 0x3F) | 0x80;
                    var c3 = (cc & 0x3F) | 0x80;
                    bstr.push(c1, c2, c3);
                }
            }
            else
            {
                bstr.push(cc);
            }
        }
        return bstr;
    }

    export function file_str2blob(string: string): Blob
    {
        var u8 = new Uint8Array(localsave.stringToUtf8Array(string));
        var blob = new Blob([u8]);
        return blob;
    }
    export function file_u8array2blob(array: Uint8Array): Blob
    {
        var blob = new Blob([array]);
        return blob;
    }
    export function save(path: string, file: Blob): number
    {
        var req = new XMLHttpRequest();//ness
        //用同步方法，本地操作
        req.open("POST", "localsave/upload.aspx" + "?r=" + Math.random(), false);

        var fdata = new FormData();
        fdata.append("path", path);
        fdata.append("file", file);
        req.send(fdata);
        var json = JSON.parse(req.responseText);
        if (json["code"] != 0)
            throw new Error(json["error"]);
        return json["code"];

    }
    export function list(path: string): any
    {
        var req = new XMLHttpRequest();//ness
        //用同步方法，本地操作
        req.open("Get", "localsave/list.aspx?path=" + path + "&r=" + Math.random(), false);
        req.send(null);
        var json = JSON.parse(req.responseText);
        return json;
    }
}